package com.evenmo.gxlcTest;


import com.evenmo.pojo.onetomany_shuangxiang.Person;
import com.evenmo.pojo.onetomany_shuangxiang.Room;
import com.evenmo.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.Set;

/**
 * @author: moyongjun
 * @Date: 2019-08-16 18:36
 * @Description: 多对一关联测试
 */
public class PersonTest3 {

    private Session session;
    private Transaction transaction;


    @Before
    public void getSession() {
        session = HibernateUtil.getSession();
        transaction = session.beginTransaction();
    }

    @Test
    public void addPersonTest() {
        //多对一
        Person person1 = new Person();
        Person person2 = new Person();
        person1.setName("test11");
        person2.setName("test12");

        Room room = new Room();
        room.setAddress("杭州西湖区五联西苑239号");
        //同一个room
        person1.setRoom(room);
        person2.setRoom(room);
        session.save(person1);
        session.save(person2);


    }

    @Test
    public void queryPerson() {

        Person person = session.get(Person.class, 7);
        System.out.println(person);

    }

    @Test
    public void queryRoom() {

        Room room = session.get(Room.class, 6);
        Set<Person> persons = room.getPersons();
        System.out.println(persons);

        for (Person p : persons) {

            System.out.println(p.getName()+"--"+p.getId());
        }


        System.out.println(room);

    }

    @After
    public void closeSession() {
        try {
            transaction.commit();
        } catch (Exception e) {
            transaction.rollback();
        } finally {
            session.close();
        }

    }
}
